# -*- coding:utf-8 -*- 
# Author: json_steve

from . import api
from flask import request, current_app, jsonify, session
from iHome.utils.response_code import RET
from iHome.utils.iamge_storage import storage_image
from iHome.models import User
from iHome import db
from iHome.constants import QINIU_DOMIN_PREFIX
from iHome.utils.common import login_required
from flask import g


# 设置验证信息
@api.route('/user/auth', methods=["POST"])
@login_required
def set_user_auth():
    """
    1.取到用户id
    2.取到user
    3.取验证信息
    4.更信息保存到数据库
    5.返回结果
    :return:
    """
    user_id = g.user_id
    data_dict = request.json
    real_name =data_dict.get('real_name')
    id_card = data_dict.get('id_card')

    try:
        user=User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询数据失败')
    if not user:
        return jsonify(errno=RET.USERERR, errmsg='用户不存在')
    user.id_card = id_card
    user.real_name = real_name

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='保存数据失败')

    return jsonify(errno=RET.OK, errmsg='ok')


#  用户名
@api.route('/user/name', methods=['POST'])
@login_required
def set_user_name():
    """
    0.todo登陆验证
    1,获取用户名
    2,用户名保存到模型中
    3,返回结果
    :return:
    """
    # 获取用户名
    name = request.json.get('name')

    # 保存到模型中
    if not name:
        return jsonify(errno=RET.PARAMERR, errmsg='参数不完整')
    # 获取用户
    #user_id = session['user_id']
    user_id = g.user_id
    try:
        user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='获取用户信息失败')
    if not user:
        return jsonify(errno=RET.USERERR,errmsg='用户不存在')
    # 更新数据库
    user.name = name
    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='保存数据错误')
    # 保存到session
    session['user_name']=name

    return jsonify(errno=RET.OK,errmsg='ok')


# 设置头像
@api.route('/user/avatar', methods=['POST'])
@login_required
def set_user_avatar():
    """
    0. todo 登陆
    1.获取上传文件
    2.上传到七牛云
    3.头像更新到模型中
    4.返回上窜的结果
    :return:
    """
    # use_id = session.get('user_id')
    user_id = g.user_id
    # print type(user_id)
    # print user_id
    # 获取上传文件
    try:
        avatar_file = request.files.get('avatar').read()  # 文档api请求对象
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    # 上传到七牛云,封装的方法可能抛异常
    try:
        url = storage_image(avatar_file)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg='上传文件错误')
    # 头像更新到模型中


    try:
        user = User.query.get(user_id)

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='获取用户失败')
    if not user:
        return jsonify(errno=RET.USERERR, errmsg='用户不存在')
    user.avatar_url = url
    # print user
    # print user.avatar_url
    try:
        # db.session.add(user) 不能加这句
        print 123
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(error=RET.DBERR, errmsg='保存用户数据失败')
    # 返回结果
    return jsonify(errno=RET.OK, errmsg='ok', data={'avatar_file': QINIU_DOMIN_PREFIX+url})


# 加载用户的名和头像
@api.route('/user')
@login_required
def get_user_name():
    """
    1.获取用户名和头像url
    2.返回
    :return:
    """
    # 加了用户验证装饰器，所以在g里查找
    user_id = g.user_id
    try:
        user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据查询错误')
    if not user:
        return jsonify(errno=RET.USERERR, errmsg='用户不存在')

    # resp_dict = {
    #     'name': user.name,
    #     'user_avatar': QINIU_DOMIN_PREFIX+user.avatar_url,
    #     'mobile': user.mobile
    # }
    return jsonify(errno=RET.OK, errmsg='ok', data=user.to_dict())


# 获取用户认证信息
@api.route('/user/auth', methods=["GET"])
@login_required
def get_user_auth():
    print 123
    """
    1,获取用户id
    2，获取用户
    3.查找信息
    4，组织参数返回
    :return:
    """
    user_id = g.user_id
    try:
        user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查找数据失败')

    if not user:
        return jsonify(errno=RET.USERERR, errmsg='用户不存在')

    # auth_dict = {
    #     'real_name':user.real_name,
    #     'id_card':user.id_card
    # }

    return jsonify(errno=RET.OK, errmsg='ok', data=user.to_auth_info())


